<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>修改密码</span>
      </div>
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="120px" style="width: 400px;">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">确认修改</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { changePassword } from '@/api/user'

export default {
  name: 'ChangePassword',
  data() {
    const validateOldPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入当前密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'))
      } else {
        callback()
      }
    }

    const validateNewPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'))
      } else if (value.length < 6) {
        callback(new Error('新密码长度不能少于6位'))
      } else if (value === this.passwordForm.oldPassword) {
        callback(new Error('新密码不能与当前密码相同'))
      } else {
        // 当新密码改变时，重新验证确认密码
        if (this.passwordForm.confirmPassword !== '') {
          this.$refs.passwordForm.validateField('confirmPassword')
        }
        callback()
      }
    }

    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, validator: validateOldPassword, trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validateNewPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    submitForm() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 直接使用密码表单数据，token由拦截器处理
          changePassword(this.passwordForm).then(response => {
            this.loading = false
            if (response.code === 200) {
              this.$message.success('密码修改成功，请重新登录')
              // 清空表单
              this.resetForm()
              // 延迟一秒后跳转到登录页
              setTimeout(() => {
                this.$store.dispatch('user/logout').then(() => {
                  this.$router.push('/login')
                })
              }, 1000)
            } else {
              this.$message.error(response.message || '密码修改失败')
            }
          }).catch(error => {
            this.loading = false
            console.error('修改密码错误:', error)
            this.$message.error(error.message || '密码修改失败')
          })
        } else {
          this.$message.error('请检查输入信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.passwordForm.resetFields()
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  max-width: 600px;
  margin: 0 auto;
}
</style>
